<?php
class ControllerCommunityViewforum extends Controller{
    public function index(){
        $this->language->load('community/viewforum');
        $this->language->load('community/community_header');
        $this->load->model('community/viewforum');

        //detect if user login
        $this->load->model('community/user');
        if($this->customer->isLogged()){
            $this->data['is_user_login']=TRUE;
        }else{
            $this->data['is_user_login']=FALSE;
        }

        //posting awarded forum points session
        if(isset($this->session->data['text_forum_points_awarded'])){
            $this->data['text_forum_points_awarded']=$this->session->data['text_forum_points_awarded'];

            unset($this->session->data['text_forum_points_awarded']);
        }else{
            $this->data['text_forum_points_awarded']='';
        }

        $userPermission=$this->model_community_user->getPermission($this->request->get,$this->customer->getForumUserType(),$this->customer->getForumUserRank());

        if($userPermission['role_id']==1 || $userPermission['role_id']==2 || ($userPermission['role_id']==3 && $userPermission['forum_mod_ids'] && in_array($this->customer->getForumUserId(),unserialize($userPermission['forum_mod_ids'])))){
            $is_mod=TRUE;
        }else{
            $is_mod=FALSE;
        }

        //if $_GET['fid'] does no exists or is empty or is not numeric, redirect
        if(!isset($this->request->get['fid']) || empty($this->request->get['fid']) || !is_numeric($this->request->get['fid'])){
            $this->redirect($this->url->link('error/not_found'));
        }

        //if user role not allowed to view forum, redirect
        if(!$userPermission['view_forum']){
            $this->session->data['forwarded_link']=$this->url->link('community/community','','SSL');
            $this->session->data['warning_type']='not_allow_view_forum';
            $this->redirect($this->url->link('community/warning'));
        }

        //if new topic is allowed for the user role
        if($userPermission['topic_publish']){
            $this->data['allow_topic']=TRUE;
        }else{
            $this->data['allow_topic']=FALSE;
        }

        //update forum read/unread status track record
        $this->model_community_viewforum->updateForumTrack($this->request->get);

        //update forum new post notification record
        $this->model_community_viewforum->updateForumNotification($this->request->get);

        //subscribe forum
        if(isset($this->request->post['subscribe-forum'])){
            $this->model_community_viewforum->subsribeForum($this->request->get);

            $this->session->data['forwarded_link']=$this->url->link('community/viewforum','fid=' . $this->request->get['fid'],'SSL');
            $this->session->data['success_type']='subscribe_forum';
            $this->redirect($this->url->link('community/success'));
        }

        //unsubscribe forum
        if(isset($this->request->post['unsubscribe-forum'])){
            $this->model_community_viewforum->unsubscribeForum($this->request->get);

            $this->session->data['forwarded_link']=$this->url->link('community/viewforum','fid=' . $this->request->get['fid'],'SSL');
            $this->session->data['success_type']='unsubscribe_forum';
            $this->redirect($this->url->link('community/success'));
        }

        //detect if subscribed to topic
        $is_subscribed=$this->model_community_viewforum->DetectSubsribeForum($this->request->get);

        $forumInfo=$this->model_community_viewforum->getForumInfo($this->request->get);

        if(!$forumInfo['forum_enabled']){
            $this->session->data['forwarded_link']=$this->url->link('community/community','','SSL');
            $this->session->data['warning_type']='not_allow_view_forum';
            $this->redirect($this->url->link('community/warning'));
        }

        //if it is not forum but a forum cat or it is not a valid form id ,redirect
        if($forumInfo['forum_type']=='3' || empty($forumInfo)){
            $this->redirect($this->url->link('error/not_found'));
        }

        $this->data['text_topics']=$this->language->get('text_topics');
        $this->data['text_replies']=$this->language->get('text_replies');
        $this->data['text_views']=$this->language->get('text_views');
        $this->data['text_last_post']=$this->language->get('text_last_post');
        $this->data['text_announcement']=$this->language->get('text_announcement');
        $this->data['headline_name']=$forumInfo['forum_name'];
        $this->data['text_by']=$this->language->get('text_by');
        
        $this->document->setTitle($forumInfo['forum_name']);        

        $this->data['breadcrumbs']=array();

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('common/home'),
            'text'      =>      $this->language->get('text_home'),
            'separator'=>      FALSE
        );

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/community'),
            'text'      =>      $this->language->get('text_community'),
            'separator' =>      $this->language->get('text_separator')
        );

        if($forumInfo['parent_id']){
            $this->data['breadcrumbs'][]=array(
                'href'      =>      $this->url->link('community/viewforum') . '&fid=' . $forumInfo['parent_id'],
                'text'      =>      $forumInfo['parent_forum_name'],
                'separator' =>      $this->language->get('text_separator')
            );
        }

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/viewforum') . '&fid=' . $this->request->get['fid'],
            'text'      =>      $forumInfo['forum_name'],
            'separator' =>      $this->language->get('text_separator')
        );

        $this->data['text_forum']=$this->language->get('text_forum');
        $this->data['text_topics']=$this->language->get('text_topics');
        $this->data['text_posts']=$this->language->get('text_posts');
        $this->data['text_latest_post']=$this->language->get('text_latest_post');
        $this->data['text_never']=$this->language->get('text_never');
        $this->data['text_no_topics']=$this->language->get('text_no_topics');
        $this->data['text_all_topics']=$this->language->get('text_all_topics');
        $this->data['text_featured_topics']=$this->language->get('text_featured_topics');
        $this->data['text_polled_topics']=$this->language->get('text_polled_topics');
        $this->data['text_topic_cat']=$this->language->get('text_topic_cat');
        $this->data['text_topic_reported']=$this->language->get('text_topic_reported');
        $this->data['text_forum_mod']=$this->language->get('text_forum_mod');

        if($is_subscribed){
            $this->data['text_subscribe']=$this->language->get('text_unsubscribe_forum');
            $this->data['text_subsribe_name']=$this->language->get('text_unsubscribe_forum_name');
        }else{
            $this->data['text_subscribe']=$this->language->get('text_subscribe_forum');
            $this->data['text_subsribe_name']=$this->language->get('text_subscribe_forum_name');
        }

        $this->data['headline_link']=$this->url->link('community/viewforum','fid=' . $this->request->get['fid'],'SSL');
        $this->data['new_topic_link']=$this->url->link('community/post/topic','fid=' . $this->request->get['fid'],'SSL');
        $this->data['reported_topic_link']=$this->url->link('community/mcp','mode=rm&action=or','SSL');
        $this->data['subscribe_action_link']=$this->url->link('community/viewforum','fid=' . $this->request->get['fid'],'SSL');
        $this->data['featured_topic_link']=$this->url->link('community/viewforum','fid=' . $this->request->get['fid'] . '&filter=feature','SSL');
        $this->data['polled_topic_link']=$this->url->link('community/viewforum','fid=' . $this->request->get['fid'] . '&filter=poll','SSL');

        if((!isset($this->request->get['filter'])) || ($this->request->get['filter']!='feature' && $this->request->get['filter']!='poll' && $this->request->get['filter']!='tcid')){
            $this->data['all_topic_link_status']='selected';
        }else{
            $this->data['all_topic_link_status']='link';
        }

        if(isset($this->request->get['filter']) && $this->request->get['filter']=='feature'){
            $this->data['featured_topic_link_status']='selected';
        }else{
            $this->data['featured_topic_link_status']='link';
        }

        if(isset($this->request->get['filter']) && $this->request->get['filter']=='poll'){
            $this->data['polled_topic_link_status']='selected';
        }else{
            $this->data['polled_topic_link_status']='link';
        }

        //get forum mods
        $modResults=$this->model_community_viewforum->getForumModerators($this->request->get);

        $this->data['mods']=array();

        foreach($modResults as $mod){
            $this->data['mods'][]=array(
                'username'      =>      $mod['username'],
                'user_link'     =>      $this->url->link('community/profile','uid=' . $mod['user_id'],'SSL')
            );
        }

        if($forumInfo['topic_category_enabled']){
            $this->data['topic_category_enabled']=TRUE;

            $this->data['topic_cats']=array();

            $topicCats=$this->model_community_viewforum->getTopicCats($this->request->get['fid']);

            $i=0;
            foreach($topicCats as $topicCat){
                $this->data['topic_cats'][]=array(
                    'topic_category_id'     =>      $topicCat['topic_category_id'],
                    'topic_category_title'  =>      $topicCat['topic_category_title'],
                    'topic_category_link'   =>      $this->url->link('community/viewforum','fid=' . $this->request->get['fid'] . '&filter=tcid' . '&tcid=' . $topicCat['topic_category_id'],'SSL')
                );

                if(isset($this->request->get['filter']) && isset($this->request->get['tcid']) && $this->request->get['tcid']==$topicCat['topic_category_id']){
                    $this->data['topic_cats'][$i]['topic_cat_link_status']='selected';
                }else{
                    $this->data['topic_cats'][$i]['topic_cat_link_status']='link';
                }

                $i++;
            }
        }else{
            $this->data['topic_category_enabled']=FALSE;
        }


        //get subforums
        $sub_forums=$this->model_community_viewforum->getSubForums($this->request->get);
        $this->data['sub_forums']=array();

        foreach($sub_forums as $sub_forum){
            $this->data['sub_forums'][]=array(
                'forum_name'                =>  $sub_forum['forum_name'],
                'forum_desc'                =>  $sub_forum['forum_desc'],
                'forum_topics'              =>  $sub_forum['forum_topics'],
                'forum_posts'               =>  $sub_forum['forum_posts'],
                'user_link'                 =>  $this->url->link('community/profile','uid=' . $sub_forum['forum_last_poster_id'] ,'SSL'),
                'forum_last_poster_name'    =>  $sub_forum['forum_last_poster_name'],
                'forum_last_post_time'      =>  date($this->language->get('date_time_format_short'),$sub_forum['forum_last_post_time']),
                'forum_link'                =>  $this->url->link('community/viewforum','fid=' . $sub_forum['forum_id'] ,'SSL')
            );

            //get subforum track
            if(!empty($sub_forums)){
                if($sub_forum['forum_posts']>0){
                    if(isset($sub_forum['mark_time'])){
                        $this->data['forumStatus'][]=($sub_forum['mark_time']>$sub_forum['forum_last_post_time']) ? 'forum_read' : 'forum_unread';
                        $this->data['text_forum_status'][]=($sub_forum['mark_time']>$sub_forum['forum_last_post_time']) ? $this->language->get('text_forum_read') : $this->language->get('text_forum_unread');
                    }else{
                        if(!$this->customer->isLogged()){
                            $this->data['forumStatus'][]='forum_read';
                            $this->data['text_forum_status'][]=$this->language->get('text_forum_read');
                        }else{
                            $this->data['forumStatus'][]='forum_unread';
                            $this->data['text_forum_status'][]=$this->language->get('text_forum_unread');
                        }
                    }
                }else{
                    $this->data['forumStatus'][]='forum_read';
                    $this->data['text_forum_status'][]=$this->language->get('text_forum_read');
                }
            }
        }
 
        //pagination
        $url='fid=' . $this->request->get['fid'];

        if(isset($this->request->get['filter'])){
            $url=$url . '&filter=' . $this->request->get['filter'];
        }
        if(isset($this->request->get['tcid'])){
            $url=$url . '&tcid=' . $this->request->get['tcid'];
        }

        $pagination = new Pagination();
        
        $pagination->total=$this->model_community_viewforum->getTopicTotal($this->request->get);
        
		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}
        
        $pagination->page = $page;
        $pagination->limit = $this->config->get('forum_max_topic_per_page');
        $pagination->url = $this->url->link('community/viewforum', $url . '&page={page}');
		
		$this->data['pagination'] = $pagination->render();

        $start=($page-1)*$pagination->limit;
        
        //get announcement_topics
        $results=$this->model_community_viewforum->getAnnouncementTopics($this->request->get);
        $this->data['announcement_topics']=array();
        $delTopicTrackStrs="";

        if($results){
            $i=0;
            foreach($results as $result){
                //update outdated stikcy topic as normal topic
                if($result['topic_type']>0 && $result['topic_time_limit']!=0 && $result['topic_time_limit']<time()){
                    $this->model_community_viewforum->UpdateTopicNormalType($result['topic_id']);
                }

                $this->data['announcement_topics'][]=array(
                    'topic_id'                  =>  $result['topic_id'],
                    'topic_title'               =>  $result['topic_title'],
                    'username'                  =>  $result['username'],
                    'topic_time'                =>  date($this->language->get('date_time_format_short'),$result['topic_time']),
                    'topic_replies'             =>  $result['topic_replies'],
                    'topic_views'               =>  $result['topic_views']+mt_rand(95,3987),
                    'topic_last_poster_name'    =>  $result['topic_last_poster_name'],
                    'topic_last_post_time'      =>  date($this->language->get('date_time_format_short'),$result['topic_last_post_time']),
                    'viewtopic_link'            =>  $this->url->link('community/viewtopic','fid=' . $result['forum_id'] . '&tid=' . $result['topic_id'],'SSL')
                );

                if(isset($result['image'])){
                    $temp=explode('.',$result['image']);
                    $name_no_ex=rtrim($result['image'],'.' . $temp[count($temp)-1]);

                    $this->data['announcement_topics'][$i]['topic_product_image']=HTTP_IMAGE . 'cache/' . $name_no_ex . '-' . $this->config->get('config_image_thumb_width') . 'x' . $this->config->get('config_image_thumb_height') . '.' . $temp[count($temp)-1];
                }

                if($is_mod && $result['topic_reported']){
                    $this->data['announcement_topics'][$i]['is_reported']=TRUE;
                }else{
                    $this->data['announcement_topics'][$i]['is_reported']=FALSE;
                }

                if($result['topic_featured']){
                    $this->data['announcement_topics'][$i]['is_featured']=TRUE;
                }else{
                    $this->data['announcement_topics'][$i]['is_featured']=FALSE;
                }

                $this->data['announcement_topics'][$i]['topic_poster_link']=$this->url->link('community/profile','uid=' . $result['user_id'],'SSL');
                $this->data['announcement_topics'][$i]['topic_last_poster_link']=$this->url->link('community/profile','uid=' . $result['topic_last_poster_id'],'SSL');

                //pagination link for topics
                $topic_pagination_link = new PaginationOnlyLink();

                $topic_pagination_link->style_links='topic-pagination';
                $topic_pagination_link->total=$result['topic_replies']+1;

                $topic_pagination_link->limit = $this->config->get('topic_max_posts_per_page');
                $topic_pagination_link->url = $this->url->link('community/viewtopic', 'fid=' . $this->request->get['fid'] . '&tid=' . $result['topic_id'] . '&page={page}');

                $this->data['announcement_topics'][$i]['topic_pagination_link'] = $topic_pagination_link->render();

                if(!empty($results)){
                    if(time()-$result['topic_last_post_time']>(int)$this->config->get('topics_be_read_time')){
                        $this->data['announcementTopicStatus'][]= $result['topic_status'] ? 'announcement_topic_locked_read' : 'announcement_topic_read';
                        $this->data['text_announcement_topic_status'][]=$this->language->get('text_topic_read');

                        if(isset($result['mark_time'])){
                            $delTopicTrackStrs.="'" . $result['topic_id'] . "',";
                        }
                    }else{
                        if(isset($result['mark_time'])){
                            if($result['topic_status']){
                                $this->data['announcementTopicStatus'][]=($result['mark_time']>$result['topic_last_post_time']) ? 'announcement_topic_locked_read' : 'announcement_topic_locked_unread';
                            }else{
                                $this->data['announcementTopicStatus'][]=($result['mark_time']>$result['topic_last_post_time']) ? 'announcement_topic_read' : 'announcement_topic_unread';
                            }

                            $this->data['text_announcement_topic_status'][]=($result['mark_time']>$result['topic_last_post_time']) ? $this->language->get('text_topic_read') : $this->language->get('text_topic_unread');
                        }else{
                            if(!$this->customer->isLogged()){
                                $this->data['announcementTopicStatus'][]= $result['topic_status'] ? 'announcement_topic_locked_read' : 'announcement_topic_read';
                                $this->data['text_announcement_topic_status'][]=$this->language->get('text_topic_read');
                            }else{
                                $this->data['announcementTopicStatus'][]= $result['topic_status'] ? 'announcement_topic_locked_unread' : 'announcement_topic_unread';
                                $this->data['text_announcement_topic_status'][]=$this->language->get('text_topic_unread');
                            }
                        }
                    }
                }

                $i++;
            }
        }

        //get normal topics
        $results=$this->model_community_viewforum->getTopics($this->request->get,$start,$pagination->limit);

        if($results){
            $this->data['has_topics']=TRUE;
        }else{
            $this->data['has_topics']=FALSE;
        }

        $this->data['topics']=array();
        $this->data['topicStatus']=array();

        if($results){
            $i=0;
            foreach($results as $result){
                //update outdated stikcy topic as normal topic
                if($result['topic_type']>0 && $result['topic_time_limit']!=0 && $result['topic_time_limit']<time()){
                    $this->model_community_viewforum->UpdateTopicNormalType($result['topic_id']);
                }

                //topic rating
                if(unserialize($result['rating'])){
                    $rating=array_sum(unserialize($result['rating']))/count(unserialize($result['rating']));

                    if($rating>=4.5 && $rating<5){
                        $rating=5;
                    }elseif($rating>4 && $rating<4.5){
                        $rating=4;
                    }elseif($rating>=3.5 && $rating<4){
                        $rating=4;
                    }elseif($rating>3 && $rating<3.5){
                        $rating=3;
                    }elseif($rating>=2.5 && $rating<3){
                        $rating=3;
                    }elseif($rating>2 && $rating<2.5){
                        $rating=2;
                    }elseif($rating>=1.5 && $rating<2){
                        $rating=2;
                    }elseif($rating>0 && $rating<1.5){
                        $rating=1;
                    }
                }else{
                    $rating=FALSE;
                }

                $this->data['topics'][]=array(
                    'topic_id'                  =>  $result['topic_id'],
                    'topic_title'               =>  $result['topic_title'],
                    'username'                  =>  $result['username'],
                    'topic_rating'              =>  $rating,
                    'topic_time'                =>  date($this->language->get('date_time_format_short'),$result['topic_time']),
                    'topic_replies'             =>  $result['topic_replies'],
                    'topic_type'                =>  $result['topic_type'],
                    'topic_views'               =>  $result['topic_views']+mt_rand(95,3987),
                    'topic_last_poster_name'    =>  $result['topic_last_poster_name'],
                    'topic_last_post_time'      =>  date($this->language->get('date_time_format_short'),$result['topic_last_post_time']),
                    'viewtopic_link'            =>  $this->url->link('community/viewtopic','fid=' . $result['forum_id'] . '&tid=' . $result['topic_id'],'SSL'),
                    'topic_category_displayed'  =>  $forumInfo['topic_category_displayed'],
                    'topic_category_title'      =>  $result['topic_category_title'],
                    'topic_category_link'       =>      $this->url->link('community/viewforum','fid=' . $this->request->get['fid'] . '&filter=tcid' . '&tcid=' . $result['topic_category_id'],'SSL')
                );

                if(isset($result['image'])){
                    $temp=explode('.',$result['image']);
                    $name_no_ex=rtrim($result['image'],'.' . $temp[count($temp)-1]);

                    $this->data['topics'][$i]['topic_product_image']=HTTP_IMAGE . 'cache/' . $name_no_ex . '-' . $this->config->get('config_image_thumb_width') . 'x' . $this->config->get('config_image_thumb_height') . '.' . $temp[count($temp)-1];
                }

                $this->data['topics'][$i]['topic_poster_link']=$this->url->link('community/profile','uid=' . $result['user_id'],'SSL');
                $this->data['topics'][$i]['topic_last_poster_link']=$this->url->link('community/profile','uid=' . $result['topic_last_poster_id'],'SSL');


                if($is_mod && $result['topic_reported']){
                    $this->data['topics'][$i]['is_reported']=TRUE;
                }else{
                    $this->data['topics'][$i]['is_reported']=FALSE;
                }

                if($result['topic_featured']){
                    $this->data['topics'][$i]['is_featured']=TRUE;
                }else{
                    $this->data['topics'][$i]['is_featured']=FALSE;
                }

                if($result['topic_solved']){
                    $this->data['topics'][$i]['is_solved']=TRUE;
                }else{
                    $this->data['topics'][$i]['is_solved']=FALSE;
                }

                //pagination link for topics
                $topic_pagination_link = new PaginationOnlyLink();

                $topic_pagination_link->style_links='topic-pagination';
                $topic_pagination_link->total=$result['topic_replies']+1;

                $topic_pagination_link->limit = $this->config->get('topic_max_posts_per_page');
                $topic_pagination_link->url = $this->url->link('community/viewtopic', 'fid=' . $this->request->get['fid'] . '&tid=' . $result['topic_id'] . '&page={page}');

                $this->data['topics'][$i]['topic_pagination_link'] = $topic_pagination_link->render();

                if(!empty($results)){
                    if(time()-$result['topic_last_post_time']>(int)$this->config->get('topics_be_read_time')){
                        switch($result['topic_type']){
                            case '0':
                                $this->data['topicStatus'][]= $result['topic_status'] ? 'topic_locked_read' : 'topic_read';
                                break;
                            case '1':
                                $this->data['topicStatus'][]= $result['topic_status']? 'topic_locked_sticky_read' : 'topic_sticky_read';
                                break;
                        }

                        $this->data['text_topic_status'][]=$this->language->get('text_topic_read');

                        if(isset($result['mark_time'])){
                            $delTopicTrackStrs.="'" . $result['topic_id'] . "',";
                        }
                    }else{
                        if(isset($result['mark_time'])){

                            switch($result['topic_type']){
                                case '0':
                                    if($result['topic_status']){
                                        $this->data['topicStatus'][]=($result['mark_time']>$result['topic_last_post_time']) ? 'topic_locked_read' : 'topic_locked_unread';
                                    }else{
                                        $this->data['topicStatus'][]=($result['mark_time']>$result['topic_last_post_time']) ? 'topic_read' : 'topic_unread';
                                    }
                                    break;
                                case '1':
                                    if($result['topic_status']){
                                        $this->data['topicStatus'][]=($result['mark_time']>$result['topic_last_post_time']) ? 'topic_locked_sticky_read' : 'topic_locked_sticky_unread';
                                    }else{
                                        $this->data['topicStatus'][]=($result['mark_time']>$result['topic_last_post_time']) ? 'topic_sticky_read' : 'topic_sticky_unread';
                                    }
                            }
                            $this->data['text_topic_status'][]=($result['mark_time']>$result['topic_last_post_time']) ? $this->language->get('text_topic_read') : $this->language->get('text_topic_unread');
                        }else{
                            if(!$this->customer->isLogged()){
                                $this->data['topicStatus'][]=$result['topic_status'] ? 'topic_locked_read' : 'topic_read';
                                $this->data['text_topic_status'][]=$this->language->get('text_topic_read');
                            }else{
                                switch($result['topic_type']){
                                    case '0':
                                        $this->data['topicStatus'][]= $result['topic_status'] ? 'topic_locked_unread' : 'topic_unread';
                                        break;
                                    case '1':
                                        $this->data['topicStatus'][]= $result['topic_status'] ? 'topic_locked_sticky_read' : 'topic_sticky_unread';
                                        break;
                                }

                                $this->data['text_topic_status'][]=$this->language->get('text_topic_unread');
                            }
                        }
                    }
                }

                $i++;
            }
        }

        // delete topics that are old enough to be in the status of being read to visitor
        $delTopicTrackStrs=rtrim($delTopicTrackStrs,',');
        if(!empty($delTopicTrackStrs)){
            $this->model_community_viewforum->deleteTopicsTrack($delTopicTrackStrs);
        }

		if(file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/community/viewforum.tpl')){
            $this->template=$this->config->get('config_template') . '/template/community/viewforum.tpl';
		}else{
            $this->template='default/template/community/viewforum.tpl';
		}	
			
        $this->children = array(
            'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header',
			'community/community_header'
		);
		
		$this->response->setOutput($this->render()); 	
  	}
}
?>